"use client";
import { login, onGithubLogin } from "@/lib/action";
import { useSearchParams, useRouter } from "next/navigation";
import { useEffect } from "react";
import { useFormState } from "react-dom";
const LoginForm = ({ session }) => {
  const [state, formAction] = useFormState(login, {});
  const searchParams = useSearchParams();
  const router = useRouter();
  useEffect(() => {
    const url = searchParams.get("callbackUrl");
    if (session?.user) {
      router.replace(url || "/");
    }
  }, [session, router, searchParams]);

  return (
    <>
      <form action={onGithubLogin}>
        <button>login with github</button>
      </form>
      <form action={formAction}>
        <input type="text" name="username" placeholder="username" />
        <input type="password" name="password" placeholder="password" />
        <button>login</button>
      </form>
      {state?.reason && <p>{state.reason}</p>}
    </>
  );
};
export default LoginForm;
